package com.lexed.dao;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lexed.pojo.Emp;
import com.lexed.test.Main;

public class Mapper {
	
	public List<Object> selectAll( String sql ) throws Exception{
		if(sql == null){
			sql = Main.sqlanger.get("selectAll");
		}
		
		PreparedStatement preparedStatement = Main.connection.prepareStatement(sql);
		
		ResultSet rs =  preparedStatement.executeQuery();
		
		Map<String,String> map = new HashMap();

		map.put("empno", "int");
		map.put("ename", "String");
		map.put("job", "String");
		map.put("mgr", "int");
		map.put("hiredate", "Date");
		map.put("sal", "double");
		map.put("comm", "double");
		map.put("deptno", "int");
		
		return  ResultMapper(rs, map, "com.lexed.pojo.Emp");
		
	}
	
	public List<Object> ResultMapper(ResultSet rs, Map<String,String> map, String className) throws Exception{
		List<Object> list = new ArrayList();
		
		Class clazz = Class.forName(className);
		
		ResultSetMetaData rsmd = rs.getMetaData();
		
		int len = rsmd.getColumnCount();
		
		while(rs.next()){
			Object obj = clazz.newInstance();
			for(int i=1;i<=len;i++){
				String colmname = rsmd.getColumnName(i);
				String typename = map.get( colmname);
				Object value = null;
				switch(typename){
				case "int":
					value = rs.getInt(colmname);
					break;
				case "String":
					value = rs.getString(colmname);
					break;
				case "Date":
					value = rs.getDate(colmname);
					break;
				case "double":
					value = rs.getDouble(colmname);
					break;
				}
				Field field = clazz.getDeclaredField(colmname);
				field.setAccessible(true);
				field.set(obj, value);
				
			}
			list.add(obj);
			
		}
		
		return list;
	}
	
	
}
